package be.dch.guice;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

import be.dch.guice.exceptions.GuiceExternalConfigReadException;
import be.dch.guice.xsd.GuiceConfiguration;

public class GuiceConfigReader {
    private static final Logger LOG = Logger.getLogger(GuiceConfigReader.class);

    public static GuiceConfiguration readConfig(final String filename) throws GuiceExternalConfigReadException {
	GuiceConfigReader.LOG.debug("Reading config from " + filename);

	GuiceConfiguration config;
	try {
	    final InputStream configStream = GuiceConfigReader.class.getResourceAsStream(filename);
	    if (null == configStream) {
		GuiceConfigReader.LOG.fatal("Could not read " + filename + " from classpath");
		throw new FileNotFoundException("GuiceConfigReader: could not read " + filename + " from classpath");
	    }
	    config = GuiceConfigReader.readConfig(configStream);

	} catch (final FileNotFoundException e) {
	    throw new GuiceExternalConfigReadException(e);
	}
	return config;
    }

    public static GuiceConfiguration readConfig(final InputStream configStream) throws GuiceExternalConfigReadException {
	GuiceConfigReader.LOG.debug("Reading config from inputStream");

	GuiceConfiguration config;
	try {
	    final JAXBContext context = JAXBContext.newInstance(GuiceConfiguration.class);
	    final Unmarshaller un = context.createUnmarshaller();
	    config = (GuiceConfiguration) un.unmarshal(new InputStreamReader(configStream));

	} catch (final JAXBException e) {
	    throw new GuiceExternalConfigReadException(e);
	}
	return config;
    }
}